package com.hqbzl.chat.utils;

import com.hqbzl.chat.protocol.Serializer;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class Config {
    final static ConcurrentHashMap<String, String> CONFIG_MAP = new ConcurrentHashMap<>();
    public static final String SERIALIZER_TYPE = "SerializerType";

    public static String getValue(String key) {
        if (CONFIG_MAP.isEmpty()) {
            load();
        }
        return CONFIG_MAP.get(key);
    }

    private static void load() {
        final Properties properties = new Properties();
        try (InputStream resourceAsStream = Config.class.getClassLoader().getResourceAsStream("config.properties")) {
            properties.load(resourceAsStream);
            final Iterator<Object> iterator = properties.keySet().iterator();
            while (iterator.hasNext()) {
                final String key = iterator.next().toString();
                final Object value = properties.get(key);
                if (key != null) {
                    CONFIG_MAP.put(key, value.toString().trim());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Serializer.Algorithm getSerializer() {
        final String type = getValue(SERIALIZER_TYPE);
        if (type == null) {
            return Serializer.Algorithm.JAVA;
        }
        final String s = type.toUpperCase();
        return Serializer.Algorithm.valueOf(s);
    }

    public static void main(String[] args) {
        String type = "json";
        final String s = type.toUpperCase();
        final Serializer.Algorithm algorithm = Serializer.Algorithm.valueOf(s);
        System.out.println("algorithm = " + algorithm);
        Arrays.stream(Serializer.Algorithm.values()).forEach(x -> x.name());
        System.out.println("Config.getValue(\"SerializerType\") = " + Config.getValue(SERIALIZER_TYPE));
    }
}
